<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :modal-style="{ maxWidth: '520px' }"
    width="90%"
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns" />

    <a-divider />

    <a-card title="机型管路" :bordered="false">
      <template #extra>
        <a-button type="primary" @click="addDevicePipe">
          <template #icon>
            <icon-plus />
          </template>
          <span>新增</span>
        </a-button>
      </template>

      <gi-edit-table
        ref="DevicePipeRef" :scroll="{ minWidth: 500 }" :columns="pipeColumns" :data="form.devicePipes"
      >
        <template #action="{ rowIndex }">
          <a-space>
            <a-button type="primary" status="danger" size="large" @click="onDeletePipe(rowIndex)">
              删除
            </a-button>
          </a-space>
        </template>
      </gi-edit-table>
    </a-card>
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { addDeviceType, getDeviceType, updateDeviceType } from '@/apis/vending/deviceType'
import { type Columns, GiForm, type Options } from '@/components/GiForm'
import { useForm } from '@/hooks'
import type { ColumnItem } from '@/components/GiEditTable'
import { useDict } from '@/hooks/app'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改设备类型' : '新增设备类型'))
const formRef = ref<InstanceType<typeof GiForm>>()
const DevicePipeRef = useTemplateRef('DevicePipeRef')

const { material_type } = useDict('material_type')

const options: Options = {
  form: {},
  btns: { hide: true },
}

const { form, resetForm } = useForm({
  devicePipes: [],
})

const columns = computed<Columns<typeof form>>(() => [
  {
    label: '类型名称',
    field: 'name',
    type: 'input',
    rules: [{ required: true, message: '请输入类型名称' }],
  },
  {
    label: '状态',
    field: 'status',
    type: 'switch',
    props: {
      type: 'round',
      defaultChecked: true,
      checkedValue: 1,
      uncheckedValue: 2,
      checkedText: '启用',
      uncheckedText: '禁用',
    },
  },
  {
    label: '描述',
    field: 'description',
    type: 'textarea',
  },
])

const pipeColumns = computed<ColumnItem[]>(() => [
  {
    type: 'input-number',
    title: '管路序号',
    dataIndex: 'name',
    required: true,
  },
  {
    type: 'select',
    title: '原料类型',
    dataIndex: 'materialType',
    props: {
      options: material_type.value,
    },
  },
  {
    type: '',
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    columnProps: {
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    formItemProps: {
      contentClass: 'arco-table-cell-align-center',
    },
  },
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

const visible = ref(false)
// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const res = await getDeviceType(id)
  Object.assign(form, res.data)
  visible.value = true
}

// 新增管路
const addDevicePipe = async () => {
  const length = form.value.devicePipes.length + 1
  form.devicePipes.push({ position: length, materialType: '' })
}
// 删除管路
const onDeletePipe = async (rowIndex: number) => {
  form.devicePipes.remove(rowIndex)
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    const valid = await DevicePipeRef.value?.formRef?.validate()
    if (isInvalid && valid) return false
    if (isUpdate.value) {
      await updateDeviceType(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addDeviceType(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onAdd, onUpdate })
</script>
